﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using OpenPasteSpider.usermodel;
using Volo.Abp.DependencyInjection;

namespace OpenPasteSpider
{
    /// <summary>
    /// 
    /// </summary>
    public class InitUpdateHandler : ISingletonDependency
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly IServiceProvider _serviceProvider;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceProvider"></param>
        public InitUpdateHandler(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 初始化并升级系统
        /// </summary>
        /// <returns></returns>
        public async Task<bool> DoInitAndUpdateAsync(IOpenPasteSpiderDbContext _dbContext)
        {

            if (_dbContext.Database.GetPendingMigrations().Any())
            {
                _dbContext.Database.Migrate();
            }

            //创建基础角色
            var adminid = 0;
            var admin = await _dbContext.UserInfo.Where(x => x.Email == "admin@spider.com").AsNoTracking().FirstOrDefaultAsync();
            if (admin == null || admin == default)
            {
                var user = new UserInfo();
                user.Email = "admin@spider.com";
                user.UserName = "管理员";
                user.CreateDate = DateTimeOffset.UtcNow.DateTime;
                user.Grade = "admin";
                user.IsEnable = true;
                user.PassWord = $"123456".ToMd5Lower();
                _dbContext.Add(user);
                await _dbContext.SaveChangesAsync();
                adminid = user.Id;

                //创建基础权限
                var rootid = await _AddRoleAsync(_dbContext, "root", "root", "最高管理权限");

                await _AddRoleAsync(_dbContext, "data", "add", "添加数据的权限");

                await _AddRoleAsync(_dbContext, "data", "update", "修改数据的权限");

                await _AddRoleAsync(_dbContext, "data", "state", "更改数据的状态权限");

                await _AddRoleAsync(_dbContext, "data", "view", "基础查看权限");

                await _AddRoleAsync(_dbContext, "data", "del", "删除数据的状态权限");

                await _AddRoleAsync(_dbContext, "user", "auth", "更改角色组绑定权限");

                await _AddRoleAsync(_dbContext, "user", "update", "更改账号权限");

                //创建组
                var groupid = 0;
                var group = await _dbContext.GradeInfo.Where(x => x.Name == "admin").AsNoTracking().FirstOrDefaultAsync();
                if (group == null || group == default)
                {
                    var item = new GradeInfo();
                    item.Name = "admin";
                    item.Desc = "管理组";
                    item.IsEnable = true;
                    _dbContext.Add(item);
                    await _dbContext.SaveChangesAsync();
                    groupid = item.Id;
                }
                else
                {
                    groupid = group.Id;
                }
                //绑定角色组

                var bind = await _dbContext.GradeRole.Where(x => x.GradeId == groupid && x.RoleId == rootid).AsNoTracking().FirstOrDefaultAsync();
                if (bind == null || bind == default)
                {
                    var item = new GradeRole();
                    item.GradeId = groupid;
                    item.RoleId = rootid;
                    _dbContext.Add(item);
                    await _dbContext.SaveChangesAsync();
                }

            }
            else
            {
                adminid = admin.Id;
            }
            return true;

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="_dbContext"></param>
        /// <param name="model"></param>
        /// <param name="role"></param>
        /// <param name="desc"></param>
        /// <returns></returns>
        private async Task<int> _AddRoleAsync(IOpenPasteSpiderDbContext _dbContext, string model, string role, string desc)
        {
            var find = await _dbContext.RoleInfo.Where(x => x.Model == model && x.Role == role).AsNoTracking().FirstOrDefaultAsync();
            if (find != null && find != default)
            {
                return find.Id;
            }
            else
            {
                var item = new RoleInfo();
                item.Role = role;
                item.Name = role;
                item.Model = model;
                item.Sort = 100;
                item.IsEnable = true;
                item.Desc = desc;
                _dbContext.Add(item);
                await _dbContext.SaveChangesAsync();
                return item.Id;
            }
        }

    }
}
